﻿using Common.Helpers;
using MasterEntities.Abstraction;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DataAccessLayer.Helper
{
    public class SelectCommand//<T> where T : class
    {
        private Type typ;
        private IDomainObject obj;
        public SelectCommand(Type typ)
        {
            // TODO: Complete member initialization
            this.typ = typ;
            this.obj = (IDomainObject)Activator.CreateInstance(typ);
        }

        public string GenerateCommand(string where)//, params Expression<Func<T, object>>[] navigationProperties)
        {
            string commandText = string.Empty;
            if (!string.IsNullOrEmpty(obj.BaseClassName()) && GlobalVariables.Instance.dbConnection == Common.Helpers.Enums.DatabaseConnection.MasterApp1)
            {
                commandText = string.Format("SELECT * FROM {0}.{1} (NOLOCK) AS fi {2} {3}.{4} (NOLOCK) AS sec ON {5}"
                    , obj.SchemaName(), obj.BaseClassName(), "JOIN", obj.SchemaName(), obj.GetTableName(), "fi.Id = sec.Id");
            }
            else
            {
                commandText = string.Format("SELECT * FROM {0}.{1}", obj.SchemaName(), obj.GetTableName());
            }

            //IDomainObject odo = null;
            //string toAdd = string.Empty;
            //if (navigationProperties != null && navigationProperties.Count() > 0)
            //    foreach (Expression<Func<T, object>> expressionItem in navigationProperties)
            //    {
            //        Type type = expressionItem.Body.Type;

            //        if (type != null)
            //            odo = (IDomainObject)Activator.CreateInstance(type);

            //        if (odo != null)
            //            toAdd = " LEFT JOIN " + odo.SchemaName() + "." + odo.GetTableName() + " as " + odo.Alias() + " (NOLOCK) ON " + odo.Alias() + ".Id = fi." + type.Name + "Id";
            //    }
            //commandText += toAdd;
            return (string.IsNullOrEmpty(where) ? commandText : commandText + " WHERE " + where);
        }
    }
}
